package com.chatplus.application.common.util;

import java.util.function.BooleanSupplier;
import java.util.function.Supplier;

/**
 * description: 包装异常抛出
 * className: com.chatplus.api.utils.ExceptionThrowContainerUtil
 *
 * @author liexuan
 * @date 13:46 - 2020/11/3.
 */
public class ThrowWrapper {

    private ThrowWrapper() {
    }


    /**
     * 封装下抛出异常，避免代码里面一堆抛出异常的语句
     *
     * @param booleanHandler 处理
     * @param supplier       exception
     * @param <T>            T
     * @throws T exception
     */
    public static <T extends Exception> void throwOnTrue(BooleanSupplier booleanHandler, Supplier<? extends T> supplier) throws T {
        if (booleanHandler.getAsBoolean()) {
            throw supplier.get();
        }
    }


    /**
     * 封装下抛出异常，避免代码里面一堆抛出异常的语句
     *
     * @param bool     boolean
     * @param supplier exception
     * @param <T>      T
     * @throws T exception
     */
    public static <T extends Exception> void throwOnTrue(boolean bool, Supplier<? extends T> supplier) throws T {
        if (bool) {
            throw supplier.get();
        }
    }


    /**
     * 封装下抛出异常，避免代码里面一堆抛出异常的语句
     *
     * @param bool     boolean
     * @param supplier exception
     * @param <T>      T
     * @throws T exception
     */
    public static <T extends Exception> void throwOnFalse(boolean bool, Supplier<? extends T> supplier) throws T {
        ThrowWrapper.throwOnTrue(!bool, supplier);
    }


    /**
     * 返回true或者抛出异常
     *
     * @param bool     boolean
     * @param supplier exception
     * @param <T>      T
     * @return boolean
     * @throws T exception
     */
    public static <T extends Exception> boolean throwOrReturn(boolean bool, Supplier<? extends T> supplier) throws T {
        if (bool) {
            return true;
        }
        throw supplier.get();
    }

    /**
     * 封装下抛出异常，避免代码里面一堆抛出异常的语句
     *
     * @param bool      true 的时候执行handle执行体
     * @param exception exception
     * @param <T>       T
     * @throws T exception
     */
    public static <T extends Exception> void throwOnTrue(boolean bool, T exception, VoidConsumer handle) throws T {
        if (bool) {
            handle.consume();
            throw exception;
        }
    }

    /**
     * 封装下抛出异常，避免代码里面一堆抛出异常的语句
     *
     * @param bool      true 的时候执行handle执行体
     * @param exception exception
     * @param <T>       T
     * @throws T exception
     */
    public static <T extends Exception> void throwOnFalse(boolean bool, T exception, VoidConsumer handle) throws T {
        ThrowWrapper.throwOnTrue(!bool, exception, handle);
    }

}
